<template>
  <div class="container">
    <div class="nav-bar">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item>前端管理</el-breadcrumb-item>
        <el-breadcrumb-item>行业分类管理</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <div class="container-main">
      <Search
        :searchList="searchList"
        size="small"
        otherText="新增行业"
        other
        @other="commonHandle({ type: 'add' })"
        @search="searchHandle('search', $event)"
        @refresh="searchHandle('refresh', $event)"
      />
      <div class="main-table">
        <el-table
          :data="tableData"
          border
          style="width: 100%"
          size="small"
          row-key="id"
          :tree-props="{ children: 'children' }"
          v-loading="tableLoading"
        >
          <el-table-column prop="sort" label="行业排序" width="200" />
          <el-table-column prop="id" label="行业编码" width="200" />
          <el-table-column prop="name" label="行业名称" width="200" />
          <el-table-column label="是否禁用" min-width="200">
            <template slot-scope="{ row }">
              <div>{{ row.parentId ? "二级行业" : "一级行业" }}</div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template slot-scope="{ row }">
              <el-button
                type="text"
                size="small"
                @click="commonHandle({ type: 'see', item: row })"
                >查看</el-button
              >
              <el-button
                type="text"
                size="small"
                @click="commonHandle({ type: 'edit', item: row })"
                >编辑</el-button
              >
              <el-button
                type="text"
                size="small"
                @click="commonHandle({ type: 'delete', item: row })"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="main-page">
        <el-pagination
          background
          :page-size="10"
          layout="prev, pager, next"
          @current-change="handleCurrentChange"
          :total="totalPage"
        />
      </div>
    </div>

    <el-dialog
      :title="
        handleType == 'add'
          ? '添加行业'
          : handleType == 'see'
          ? '查看行业'
          : '修改行业'
      "
      :visible.sync="handleDialog"
      top="5vh"
    >
      <div style="max-height: 400px; overflow: scroll;">
        <el-form
          ref="submitForm"
          :model="formData"
          label-width="120px"
          :rules="rules"
        >
          <el-form-item label="行业名称" prop="name">
            <el-input
              v-model="formData.name"
              size="mini"
              :disabled="handleType == 'see'"
              :maxlength="10"
            ></el-input>
          </el-form-item>
          <el-form-item label="行业级别" prop="level">
            <el-radio-group
              v-model="formData.level"
              size="mini"
              :disabled="handleType == 'see'"
            >
              <el-radio label="1">一级行业</el-radio>
              <el-radio label="2">二级行业</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            label="行业级别"
            prop="parentId"
            v-if="formData.level == 2"
          >
            <el-select
              v-model="formData.parentId"
              placeholder="请选择父级行业"
              size="mini"
              :disabled="handleType == 'see'"
            >
              <el-option
                v-for="(item, index) in parentList"
                :key="index"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="行业排序" prop="sort">
            <el-input
              v-model="formData.sort"
              size="mini"
              :disabled="handleType == 'see'"
              :maxlength="10"
            ></el-input>
          </el-form-item>
          <el-form-item label="行业备注" prop="remark">
            <el-input
              type="textarea"
              v-model="formData.remark"
              size="mini"
              :disabled="handleType == 'see'"
              :maxlength="200"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer" v-if="handleType != 'see'">
        <el-button @click="handleDialog = false" size="mini">取 消</el-button>
        <el-button type="primary" @click="submitHandle()" size="mini"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Search from "../../components/Common/Search";
export default {
  created() {
    this._getPage();
  },
  data() {
    return {
      searchList: [
        { value: "", key: "name", type: "input", placeholder: "请输入行业名称" }
      ],
      searchForm: {},
      level1Data: [],
      tableData: [],
      tableLoading: false,
      currentPage: 1,
      totalPage: 0,
      handleType: "see",
      formData: {},
      currentHandleId: "",
      handleDialog: false,
      rules: {
        // name: [
        //   { required: true, message: '请输入行业名称', trigger: 'blur' },
        // ],
        // level: [
        //   { required: true, message: '请输入行业编码', trigger: 'blur' },
        // ],
        // sort: [
        //   { required: true, message: '请输入排序号', trigger: 'blur' },
        // ],
        // parentId: [
        //   { required: true, message: '请选择', trigger: 'blur' },
        // ]
      }
    };
  },

  components: {
    Search
  },

  computed: {
    parentList() {
      return this.level1Data.filter(item => item.id !== this.formData.id);
    }
  },

  watch: {},

  methods: {
    commonHandle({ type, item }) {
      this.handleType = type;
      if (type === "edit" || type === "see") {
        this.handleDialog = true;
        this.currentHandleId = item.id;
        this._loadById(item.id);
      } else if (type === "delete") {
        this._deleteById(item.id);
      } else if (type === "add") {
        this.handleDialog = true;
        this.formData = {
          level: "1",
          sort: this.totalPage + 1
        };
      }
    },
    searchHandle(type, form) {
      this.searchForm = form;
      if (type === "search") {
        this._getPage(form);
      } else if (type === "refresh") {
        this._getPage();
        this.searchList.forEach(item => {
          item.value = "";
        });
      }
    },
    // 删除单个行业
    _deleteById(id) {
      this.$confirm(`您真的要删除此行业吗`, `温馨提示`, {
        confirmButtonText: "确定",
        cancelButtonText: "取消"
      }).then(() => {
        this.$api.classificationDelete(id).then(res => {
          if (res.code === 200) {
            this.$message.success("删除成功");
            this._getPage();
          } else {
            this.$message.warning(res.text || "服务器出现错误");
          }
        });
      });
    },
    // 新增/修改行业提交
    submitHandle() {
      this.$refs["submitForm"].validate(valid => {
        if (valid) {
          let API = "classificationUpdate";
          if (this.handleType === "add") {
            API = "classificationCreate";
          }

          this.formData.parentId =
            this.formData.level === "1" ? "" : this.formData.parentId;

          this.$api[API](this.formData, this.currentHandleId).then(res => {
            if (res.code === 200) {
              this.$message({
                message: "操作成功",
                type: "success"
              });
              this._getPage();
              this.handleDialog = false;
            } else {
              this.$message({
                message: res.text,
                type: "warning"
              });
            }
          });
        }
      });
    },
    // 获取行业列表
    async _getPage(form = {}) {
      this.tableLoading = true;
      const res = await this.$api.classificationPage({
        page: this.currentPage,
        size: 10,
        ...form
      });

      this.tableLoading = false;
      if (res.code === 200) {
        // 一级行业
        this.level1Data = res.data.rows.filter(item => item.level === "1");
        let level2Data = res.data.rows.filter(item => item.level === "2");

        this.level1Data.forEach(one => {
          one.children = [];
          level2Data.forEach(two => {
            if (two.parentId === one.id) {
              one.children.push(two);
            }
          });
        });

        this.tableData =
          this.level1Data.length > 0 ? this.level1Data : level2Data;
        this.totalPage = +res.data.total;
      }
    },
    // 获取某个行业信息
    async _loadById(id) {
      const res = await this.$api.classificationLoad(id);
      if (res.code === 200) {
        this.formData = res.data;
      }
    }
  }
};
</script>
<style lang="scss" scoped></style>
